/**
 * Created by Administrator on 2017/11/23.
 */
import React, {Component}from 'react';
import {connect} from 'dva';
import AuditResult from './AuditResult';
import {routerRedux, Link} from 'dva/router';
import {
    Row,
    Table,
    Col,
    Card,
    Form,
    Input,
    Select,
    Tabs,
    Badge,
    Icon,
    Button,
    Dropdown,
    Menu,
    InputNumber,
    DatePicker,
    Modal,
    message
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Distributor.less';
import DistributroTable from '../../components/Distributor';
import ExamineIndex from '../../components/Distributor/ExamineIndex';
import form from "../../models/form";
const Option = Select.Option;
const FormItem = Form.Item;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');
const { TabPane } = Tabs;
@connect(state => ({
    distributor: state.distributor
}))
@Form.create()
export default class Distributor extends Component {
    state = {
        selectStatus:'',
        distributor: [],
        modalVisible: false,
        addInputValue: '',
        selectValue: 0,
        selectedRowKeys: '',
        userId: '',
        keys:'unExamine',
        record:{},
        unExamine:0,
        ExaminePass:0,
        ExamineUnPass:0,
        id:'',
        seller_name:'',
        phone:'',
        user_name:''
    }

    componentDidMount() {
        this.props.dispatch({
            type: 'distributor/queryDistributor',
            payload: {
                status: 0,
                taskType: 0,
            }
        })
    }
    componentWillReceiveProps(nextProps){
        if(nextProps.distributor.amount.length!==0 )
        this.setState({
            unExamine:nextProps.distributor.amount[0].mount,
            ExaminePass:nextProps.distributor.amount[1].mount,
            ExamineUnPass:nextProps.distributor.amount[2].mount,
        })
    }
    handlesOk = () => {
        let obj = JSON.parse(localStorage.getItem("userInfoState")).userInfo;
        const {addInputValue, selectValue, selectedRowKeys, userId,id,seller_name,phone,user_name} = this.state;

        this.props.dispatch({
            type: 'distributor/newUpdateDistributor',
            payload: {
                taskId: selectedRowKeys,
                status: selectValue,
                adminId: obj.user_id,
                checkRemark: addInputValue,
                userId: userId,
                examine: 'distributor',
                id:id,
                seller_name:seller_name,
                user_name:user_name,
                phone:phone,
            },
            callback:(response) => {
                if (response.result === 0) {
                    message.success('提交成功');
                    this.props.dispatch(routerRedux.push('/distributorManage/auditResult'));
                    // this.props.dispatch({
                    //     type: 'distributor/queryDistributor',
                    //     payload: {
                    //         status: 0,
                    //         taskType: 0,
                    //     }
                    // })
                    // this.props.handleModalSuccess(this.props.pagination);
                } else {
                    hashHistory.push({pathname:'/distributorManage/auditResult',state:'1'});
                    message.error('提交失败');
                }
            },

        })
        this.setState({
            modalVisible: false,
            addInputValue: '',
            selectValue: 0,
            selectedRowKeys: '',
            userId: '',
        })

        // this.props.dispatch({
        //     type: 'distributor/queryDistributor',
        //     payload: {
        //         status: 0,
        //         taskType: 0,
        //     }
        // })
    }

    handleSubmit = (e) => {
        let obj = JSON.parse(localStorage.getItem("userInfoState")).userInfo;
        const {addInputValue, selectValue, selectedRowKeys, userId,id,seller_name,phone,user_name} = this.state;
        e.preventDefault();
        const {dispatch, form} = this.props;
        form.validateFields((err, fieldValue) => {
            if (err) return;
            const values = {
                ...fieldValue,
            };
            dispatch({
                type: 'distributor/newUpdateDistributor',
                payload: {
                    taskId: selectedRowKeys,
                    status: selectValue,
                    adminId: obj.user_id,
                    userId: userId,
                    examine: 'distributor',
                    id:id,
                    checkRemark:values.addInputValue,
                    seller_name:values.seller_name,
                    phone:values.phone,
                    user_name:values.user_name
                },
                callback:(response) => {
                    if (response.result === 0) {
                        message.success('提交成功');
                        dispatch({
                            type:'distributor/keepData',
                            payload:{
                                selectStatus:this.state.selectStatus
                            }
                        })
                        this.props.dispatch(routerRedux.push('/distributorManage/auditResult'));
                    } else {
                        hashHistory.push({pathname:'/distributorManage/auditResult',state:'1'});
                        message.error('提交失败');
                    }
                },
            });
            this.setState({
                modalVisible: false,
                addInputValue: '',
                selectValue: 0,
                selectedRowKeys: '',
                userId: '',
            })
        });
    }


    handlesCancel = (flag) => {
        this.setState({
            modalVisible: !!flag,
        })
    }
    handleChange = (record, flag) => {
        this.state.selectStatus = flag;
        this.setState({
            modalVisible: true,
            selectValue: flag,
            selectedRowKeys: record.task_id,
            userId: record.user_id,
            distributor: this.state.distributor,
            record:record,
            id:record.id,
            seller_name:record.seller_name,
            phone:record.phone,
            user_name:record.user_name,
        });
    }
    handleTableChange = (pagination, filtersArg, sorter) => {
        const filters = Object.keys(filtersArg).reduce((obj, key) => {
            const newObj = {...obj};
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});

        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...filters,
        };

        if (sorter.field) {
            params.sorter = `${sorter.field}_${sorter.order}`;
        }
        this.handleJump(params);
    }
     handleJump=(params)=>{
        if(this.state.keys==='unExamine'){
            params["status"]=0;
            params["taskType"]=0;
            this.props.dispatch({
                type:'distributor/queryDistributor',
                payload:params,
            })
        }else if(this.state.keys==='examinePass'){
            params["status"]=1;
            params["taskType"]=0;
            this.props.dispatch({
                type:'distributor/queryPassAndUnPass',
                payload:params,
            })
        }else if(this.state.keys==='examineUnPass'){
            params["status"]=2;
            params["taskType"]=0;
            this.props.dispatch({
                type:'distributor/queryPassAndUnPass',
                payload:params,
            })
        }
    }
    handleInput = (e) => {
        this.setState({
            addInputValue: e.target.value,
        })
    }
    handleTabChange=(key)=>{
        this.setState({
            keys:key,
        })
        const params={};
        if(key==='unExamine'){
            params["status"]=0;
            params["taskType"]=0;
            this.props.dispatch({
                type:'distributor/queryDistributor',
                payload:params,
            })
        }else if(key==='examinePass'){
            params["status"]=1;
            params["taskType"]=0;
            this.props.dispatch({
                type:'distributor/queryPassAndUnPass',
                payload:params,
            })
        }else if(key==='examineUnPass'){
            params["status"]=2;
            params["taskType"]=0;
            this.props.dispatch({
                type:'distributor/queryPassAndUnPass',
                payload:params,
            })
        }
    }

    render() {
        const {distributor: {loading: ruleLoading, Data,passAndUnPass}} = this.props;
        const {modalVisible, addInputValue,ExamineUnPass,ExaminePass,unExamine} = this.state;
        // const {seller_name,phone,user_name}=this.state;

        const record=this.state.record;
        const {getFieldDecorator, getFieldValue} = this.props.form;
        const formInitValue = record;

        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 7},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 12},
                md: {span: 10},
            },
        };

        const submitFormLayout = {
            wrapperCol: {
                xs: {span: 24, offset: 0},
                sm: {span: 10, offset: 7},
            },
        };

        return (
            <PageHeaderLayout title="分销商审核">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <Tabs defaultActiveKey="unExamine" onChange={this.handleTabChange} size="large" tabBarStyle={{ marginBottom: 24 }}>

                            <TabPane tab={<span>未审核<Badge count={unExamine} showZero={true}/></span> } key="unExamine">
                                <DistributroTable
                                    data={Data}
                                    loading={ruleLoading}
                                    onChange={this.handleTableChange}
                                    handleChange={this.handleChange}/>
                            </TabPane>

                            <TabPane tab={<span>审核通过<Badge count={ExaminePass} showZero={true}/></span> } key="examinePass">
                                <ExamineIndex
                                    data={passAndUnPass}
                                    loading={ruleLoading}
                                    onChange={this.handleTableChange}/>
                            </TabPane>
                            <TabPane tab={<span>审核未通过<Badge count={ExamineUnPass} showZero={true}/></span> }key="examineUnPass">
                                <ExamineIndex
                                    data={passAndUnPass}
                                    loading={ruleLoading}
                                    onChange={this.handleTableChange}/>
                            </TabPane>
                        </Tabs>
                        <Modal title="审核说明" visible={modalVisible} onOk={this.handlesOk}
                               onCancel={() => this.handlesCancel(false)}
                               footer={null}
                        >
                            <Form
                                onSubmit={this.handleSubmit}
                                >
                                <FormItem
                                    {...formItemLayout}
                                    label="商店名"
                                >
                                    {getFieldDecorator('seller_name', {
                                        initialValue:  formInitValue.seller_name || '',
                                    })(
                                        <Input placeholder="商店名"/>
                                    )}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label="申请人"
                                >
                                    {getFieldDecorator('user_name', {
                                        initialValue:  formInitValue.user_name || '',
                                    })(
                                        <Input placeholder="申请人"/>
                                    )}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label="电话号码"
                                >
                                    {getFieldDecorator('phone', {
                                        initialValue:  formInitValue.phone || '',
                                    })(
                                        <Input placeholder="电话号码"/>
                                    )}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label="描述"
                                >
                                    {getFieldDecorator('addInputValue', {
                                        initialValue:'',
                                    })(
                                        <Input placeholder="描述"/>
                                    )}
                                </FormItem>
                                <FormItem {...submitFormLayout} style={{marginTop: 32}}>
                                    <Button type="primary" onClick={this.handleSubmit}>
                                        提交
                                    </Button>
                                    <Button style={{marginLeft: 8}} onClick={() => this.handlesCancel(false)}>取消</Button>
                                </FormItem>
                            {/*<FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label="商店名">*/}
                                {/*<Input value={seller_name} />*/}
                            {/*</FormItem>*/}
                            {/*<FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label="申请人">*/}
                                {/*<Input value={user_name} />*/}
                            {/*</FormItem>*/}
                            {/*<FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label="电话号码">*/}
                                {/*<Input value={phone} />*/}
                            {/*</FormItem>*/}
                            {/*<FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label="描述">*/}
                                {/*<Input placeholder="请输入" onChange={this.handleInput} value={addInputValue}/>*/}
                            {/*</FormItem>*/}
                            </Form>
                        </Modal>
                    </div>
                </Card>

            </PageHeaderLayout>


        )
    }
}